# Перечень этапов 
stages:
  - build
  - test
  - coverage
  - delivery
  - deploy

variables:
  WINDOWS_SUPPORT_URL: "https://gitlab.com/mfetisov_lsx/simodo/deploy-windows.git"

.save_dir_to_env_var: &save_dir_to_env_var
  - __GITLAB_CI_last_location_dir__=$PWD

.return_to_saved_dir: &return_to_saved_dir
  - cd $__GITLAB_CI_last_location_dir__

# Шаблон Alt p10

## Устанавливаем общие программы для сборки

.download_build_programs_alt_p10: &download_build_programs_alt_p10
  # Обновляем список пакетов в репозиториях
  - apt-get update -y
  # Ставим пакеты для сборки
  - apt-get install -y cmake make gcc gcc-c++ qt5-base-devel qt5-charts-devel qt5-datavis3d-devel qt5-svg-devel boost-devel boost-filesystem-devel boost-asio-devel boost-interprocess-devel qt5-tools

.before_alt: &before_alt
  - *download_build_programs_alt_p10
  # Создаём рабочие каталоги
  - ./configure

.alt_p10_template:
  image: alt:p10
  before_script: *before_alt

# Шаблон Ubuntu jammy

## Устанавливаем общие программы для сборки

.download_build_programs_ubuntu: &download_build_programs_ubuntu_jammy
  # Обновляем список пакетов в репозиториях
  - apt -y update
  # Ставим пакеты для сборки
  ## qttools5-dev-tools зависит от tzdata
  - DEBIAN_FRONTEND=noninteractive apt install -y --no-install-recommends tzdata
  - apt -y install cmake g++ qt5-qmake qtbase5-dev libqt5charts5-dev libqt5datavisualization5-dev libqt5svg5-dev wget qttools5-dev-tools
  - wget https://boostorg.jfrog.io/artifactory/main/release/1.82.0/source/boost_1_82_0.tar.gz
  - tar -zxf boost_1_82_0.tar.gz
  - cd boost_1_82_0
  - ./bootstrap.sh --with-libraries=filesystem
  - ./b2 install
  - cd ..

.make_translator_aliases: &make_translator_aliases
  - lrelease-qt5() { lrelease $@; }
  - export -f lrelease-qt5
  - lupdate-qt5() { lupdate $@; }
  - export -f lupdate-qt5

.before_ubuntu: &before_ubuntu
  - *download_build_programs_ubuntu_jammy
  - *make_translator_aliases
  # Создаём рабочие каталоги
  - ./configure

.ubuntu_jammy_template:
  image: ubuntu:jammy
  before_script: *before_ubuntu

# Windows

.download_cross_compile_programs_ubuntu_jammy: &download_cross_compile_programs_ubuntu_jammy
  # Устанавливаем пакеты
  - apt -y update
  - apt -y install git make libxcb-glx0 libx11-xcb1 libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-randr0 libxcb-render-util0 libxcb-shape0 libxcb-sync1 libxcb-xfixes0 libxcb-xinerama0 libxcb-xkb1 libxkbcommon-x11-0 libegl1 libpcre2-16-0 libgl1 libjpeg-dev wget

# Build
# Собираем проект

.build_template:
  stage: build
  script:
    # Собираем
    - go/make
    # Автотесты
    - test/libs

  artifacts:
    paths:
      - bin/*
    expire_in: 30 minutes

  except:
    - prod
    - test-prod

build alt p10:
  extends:
    - .build_template
    - .alt_p10_template

build ubuntu jammy:
  extends:
    - .build_template
    - .ubuntu_jammy_template

build windows 10:
  stage: build
  image: ubuntu:jammy
  variables:
    __support_url__: "$WINDOWS_SUPPORT_URL"
  script:
    - *download_cross_compile_programs_ubuntu_jammy

    # Скачивание утилит и фреймворков
    - git clone --depth 1 $__support_url__ cross
    - __support_dir__=$PWD/cross
    - *save_dir_to_env_var
 
    # Распаковка mxe
    - cd /opt
    # - cat $__support_dir__/mxe.tar.gz.* | tar -zxf -
    - tar -zxf $__support_dir__/mxe.tar.gz
    - chmod -R +x .
    - export PATH=$PWD/mxe/usr/bin:$PWD/mxe/usr/x86_64-w64-mingw32.shared/qt5/bin:$PATH
    - *make_translator_aliases
    - *return_to_saved_dir

    # Сборка проекта
    - ./configure
    - go/crossmake

  only:
    - merge_requests

# Coverage
## Получение информации о покрытии тестами для код-ревью

# Получение информации о покрытии тестами для код-ревью

coverage-for-merge-requests:
  stage: coverage
  extends: .ubuntu_jammy_template
  script:
    # Устанавливаем пакеты
    - apt-get -y install gcovr
    # Собираем
    - go/makec
    # Прогоняем тест
    - test/libs
    # Получаем и сохраняем отчёт XML
    - export PATH="$PWD/cov-support:$PATH"
    - gcovr --xml-pretty --exclude-unreachable-branches --print-summary -o coverage.xml --root ${CI_PROJECT_DIR}

  # Начиная с 14 версии GitLab
  artifacts:
    expire_in: 30 days
    reports:
      coverage_report:
        coverage_format: cobertura
        path: ./coverage.xml

  # Для старых версий GitLab (дло 14)
  # artifacts:
  #   name: ${CI_JOB_NAME}-${CI_COMMIT_REF_NAME}-${CI_COMMIT_SHA}
  #   expire_in: 30 days
  #   reports:
  #     cobertura: ./coverage.xml

  only:
    - merge_requests

# Delivery

.delivery_template:
  stage: delivery
  dependencies: []

  # Установка gitlab-release-cli
  # - apt-get -y install curl
  # - curl --location --output /usr/local/bin/release-cli "https://gitlab.com/api/v4/projects/gitlab-org%2Frelease-cli/packages/generic/release-cli/latest/release-cli-linux-amd64"
  # - sudo chmod +x /usr/local/bin/release-cli
  # - release-cli -v
  # release:
  #   tag_name: '0.2.0'
  #   name: 'Release 0.2.0'
  #   description: 'Release created using the release-cli.'

  artifacts:
    paths:
      - packages/*
    expire_in: 120 days

  only:
    - prod
    - test-prod

.download_linux_support: &download_linux_support
  - __last_loc_dir__=$PWD
  - git clone --depth 1 $__support_url__ support
  - __support__=$PWD/support

.unpack_deploylinuxqt: &unpack_deploylinuxqt
  - mkdir linuxdeployqt
  - cd linuxdeployqt
  - tar -zxf $__support__/linuxdeployqt.tar.gz
  - export PATH=$PWD/bin:$PATH
  - cd $__last_loc_dir__

.unpack_ifw_with_static_qt: &unpack_ifw_with_static_qt
  - mkdir -p Qt/QtIFW
  - cd Qt/QtIFW
  - tar -zxf $__support__/QtIFW.tar.gz
  - cd $__last_loc_dir__

.do_deploy: &do_deploy
  - go/make
  - go/deploy

.download_servers: &download_servers
  - mkdir -p data/servers
  - rm -rf data/servers/*
  - cd data/servers
  - SERVER_HOST_URL=http://simodo.ru/distros/stars
  - wget $SERVER_HOST_URL/$__servers_url__/simodo-server.tar.gz
  - wget $SERVER_HOST_URL/$__servers_url__/language-server.tar.gz
  - tar -zxf simodo-server.tar.gz
  - tar -zxf language-server.tar.gz
  - rm -f simodo-server.tar.gz language-server.tar.gz
  - cd ../..

delivery alt:
  extends:
    - .delivery_template
    - .alt_p10_template

  variables:
    __support_url__: "https://gitlab.com/mfetisov_lsx/simodo/deploy-alt.git"
    __servers_url__: "alt/p10/0.4.5-UTC_2024.04.12_18.56.x86_64/bin"
  script:
    # Устанавливаем пакеты
    ## support зависит от git, linuxdeployqt
    ## libqxcb.so зависит от libpango, libgdk-pixbuf
    ## libopenglrenderer.so зависит от qt5-3d
    ## platformthemes, platforminputcontext, iconengines, platforms, xcbglintegrations зависит от plasma5-integration
    ## styles зависит от plasma5-breeze
    ## kio зависит от kf5-kio
    - apt-get -y install git linuxdeployqt libpango libgdk-pixbuf plasma5-integration plasma5-breeze kf5-kio wget

    - *download_linux_support
    - *unpack_ifw_with_static_qt

    - *download_servers

    - *do_deploy

delivery ubuntu:
  extends:
    - .delivery_template
    - .ubuntu_jammy_template

  variables:
    __support_url__: "https://gitlab.com/mfetisov_lsx/simodo/deploy-ubuntu.git"
    __servers_url__: "ubuntu/jammy/0.4.5-UTC_2024.04.12_18.57.x86_64/bin"
  script:
    # Устанавливаем пакеты
    ## support зависит от git
    ## linuxdeployqt зависит от patchelf
    ## platformthemes, platforminputcontext, iconengines, platforms, xcbglintegrations, styles, kio зависит от plasma-integration
    ## geometryloaders зависит от qt3d-defaultgeometryloader-plugin, qt3d-gltfsceneio-plugin
    - apt -y install git patchelf plasma-integration wget

    - *download_linux_support
    - *unpack_deploylinuxqt
    - *unpack_ifw_with_static_qt

    - *download_servers

    - *do_deploy

delivery windows:
  extends: .delivery_template

  image: ubuntu:jammy

  variables:
    __support_url__: "$WINDOWS_SUPPORT_URL"
    __servers_url__: "windows/10/0.4.5-UTC_2024.04.12_17.12.x86_64/bin"
  script:
    - *download_cross_compile_programs_ubuntu_jammy

    # Скачивание утилит и фреймворков
    - git clone --depth 1 $__support_url__ cross
    - __support_dir__=$PWD/cross
    - *save_dir_to_env_var
 
    # Распаковка mxe
    - cd /opt
    # - cat $__support_dir__/mxe.tar.gz.* | tar -zxf -
    - tar -zxf $__support_dir__/mxe.tar.gz
    - chmod -R +x .
    - export PATH=$PWD/mxe/usr/bin:$PWD/mxe/usr/x86_64-w64-mingw32.shared/qt5/bin:$PATH
    - *make_translator_aliases
    - *return_to_saved_dir

    # Установка QtIFW
    - mkdir -p Qt/QtIFW/bin
    - cd Qt/QtIFW/bin
    - echo \#\!/bin/bash > binarycreator
    - echo /opt/mxe/usr/bin/x86_64-pc-linux-gnu-binarycreator -t /opt/mxe/usr/x86_64-w64-mingw32.static/qt5/bin/installerbase.exe \$\@ >> binarycreator
    - chmod +rwx binarycreator
    - *return_to_saved_dir

    - *download_servers
    - mkdir -p data/servers/lsp/bin 
    - cp data/servers/language-server/bin/*dll data/servers/lsp/bin/ 

    # Сборка проекта
    - ./configure
    - go/crossmake

    # Распаковка зависимостей редактора
    - cd bin
    - tar -zxf $__support_dir__/qt_runtime.tar.gz
    - tar -zxf $__support_dir__/boost_runtime.tar.gz
    - *return_to_saved_dir

    # Развёртывание проекта
    - go/deploy

    # Переименовываем расширения дистрибутивов
    - cd packages
    - for i in *; do mv "$i" "${i/run/exe}"; done;

# Pages
## Используем GitLab Pages для публикации Doxygen-документации и отчёта покрытия тестами

pages:
  stage: delivery
  extends: .alt_p10_template
  dependencies: []
  script:
  # Устанавливаем пакеты
  - apt-get -y install doxygen graphviz lcov
  - apt-get install -y fonts-ttf-dejavu
  # Прогоняем Doxygen
  - go/doxy
  # Собираем
  - go/makec
  # Прогоняем тест
  - test/libs
  # Получаем и сохраняем отчёт HTML
  - export PATH="$PWD/cov-support:$PATH"
  - lcov -t "SIMODO shell" -o sidmodo-shell.info -c -d . --no-external
  - genhtml -o coverage sidmodo-shell.info
  # Деплоим
  - mv doc/html/ public/
  - mv coverage/ public/coverage/

  coverage: /^\s*lines\.*:\s+\d+\.\d+%/

  artifacts:
    paths:
    - public
    expire_in: 120 days
  only:
    - dev

# Deploy

.deploy_template:
  stage: deploy
  image: alt:p10
  script:
  - apt-get -y update
  - apt-get -y install openssh sshpass zip
  - ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa
  - DISTRO_FILENAME=$(ls packages)
  - VERSION_STRING=$(echo $DISTRO_FILENAME | sed -e 's/simodo-shell-//' | sed -e "s/$__deploy_ext__//")
  - mkdir $VERSION_STRING
  - cd packages
  - tar -zcf $DISTRO_FILENAME.tar.gz $DISTRO_FILENAME
  - zip $DISTRO_FILENAME.zip $DISTRO_FILENAME
  - cd ..
  - cp packages/* $VERSION_STRING/
  - sshpass -f "$SSH_EXTERNAL_SERVER_PASSWORD" scp -o StrictHostKeyChecking=no -P $SSH_EXTERNAL_SERVER_PORT -r ./$VERSION_STRING $SSH_EXTERNAL_SERVER_USERNAME@$SSH_EXTERNAL_SERVER_HOST:~/simodo.ru/htdocs/www/distros/simodo-shell/$__deploy_url__
  only:
    - prod

deploy alt:
  extends: .deploy_template
  dependencies:
    - delivery alt
  variables:
    __deploy_ext__: ".run"
    __deploy_url__: "alt/p10/"

deploy ubuntu:
  extends: .deploy_template
  dependencies:
    - delivery ubuntu
  variables:
    __deploy_ext__: ".run"
    __deploy_url__: "ubuntu/jammy/"

deploy windows:
  extends: .deploy_template
  dependencies:
    - delivery windows
  variables:
    __deploy_ext__: ".exe"
    __deploy_url__: "windows/10/"

# Other
## Пригодится при отладке непрерывной доставки

.remove_utils: &remove_utils
  - rm -rf ../../Qt ../../linuxdeployqt ../../cross /opt/mxe ../../support

.build_deploylinuxqt: &build_deploylinuxqt
  # Сборка linuxdeployqt
  - git clone https://github.com/probonopd/linuxdeployqt.git
  - cd linuxdeployqt
  - qmake && make
  - export PATH=$PWD/bin:$PATH
  - cd ..

.build_ifw_with_static_qt: &build_ifw_with_static_qt
  # Сборка Qt5 из исходников
  - mkdir Qt
  - cd Qt
  - mkdir Qt5-static
  - git clone git://code.qt.io/qt/qt5.git Qt5-source
  - cd Qt5-source
  - git checkout ifw-5.15.2
  - ./init-repository --module-subset=qtbase,qtdeclarative,qttools,qttranslations,qtwayland,qtx11extras
  - sed -i 's/#ifdef __cplusplus/#ifdef __cplusplus\n#  include <limits>/' qtbase/src/corelib/global/qglobal.h
  - ./configure -prefix $PWD/../Qt5-static -opensource -confirm-license -release -static -static-runtime -platform linux-clang -accessibility -qt-zlib -qt-libpng -qt-libjpeg -qt-pcre -no-glib -no-cups -no-sql-sqlite -no-qml-debug -no-opengl -no-egl -no-sm -no-icu -nomake examples -nomake tests -no-libudev
  - make -j8 module-qtbase module-qtdeclarative module-qttools module-qttranslations module-qtwayland module-qtx11extras
  - make install
  - cd ../Qt5-static
  - export PATH=$PWD/bin:$PATH
  - cd ../..
  # Сборка IFW из исходников
  - cd Qt
  - git clone https://github.com/qtproject/installer-framework.git QtIFW
  - cd QtIFW
  - echo "CONFIG += libarchive"$'\n' > installerfw.pri.tmp
  - cat installerfw.pri >> installerfw.pri.tmp
  - rm -f installerfw.pri
  - cp installerfw.pri.tmp installerfw.pri
  - qmake && make -j8
  - cd ../..
  - PATH=$(echo $PATH | sed 's/.*Qt5-static\/bin://')
